import { getUser, getRoomList, changeRoomStatus } from '../../api/login'
const app = getApp()

Page({
  data: {
    userData: {},
    roomList: [], // 广场直播间
    currentRoom: {} // 自己直播间
  },
  // 我要开播
  async handleLive() {
    // 将 room_status 的值改为 2
    app.isLive = true
    const data = { type: 2, im_id: this.data.currentRoom.im_id}
    await changeRoomStatus(data)

    app.liveInfo = this.data.currentRoom
    wx.navigateTo({
      url: '/pages/live/live'
    })
  },
  handleEvent(event) { 
    if (event.detail.room_status) {
      app.liveInfo = event.detail
      wx.navigateTo({
        url: '/pages/live/live'
      })
    } else {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '该用户未开通直播间'
      })
    }
  },
  async getRoomList() {
    const res = await getRoomList()
    wx.stopPullDownRefresh()
    const roomList = res.rooms.filter(item => item.room_owner !== this.data.userData.id)
    const currentRoom = res.rooms.filter(item => item.room_owner === this.data.userData.id)[0]
    this.setData({
      roomList,
      currentRoom
    })
  },
  _auth() {
    wx.login({
      success: async (res) => {
        const data = {code: res.code}
        const result = await getUser(data)
        if (result.code === 1) {
          wx.navigateTo({
            url: '/pages/login/login'
          })
        } else {
          this.setData({
            userData: result.user
          })
          app.userData = result.user
          this.getRoomList()
        }
      }
    })
  },
  onShow() {
    if (!this.data.userData.id) {
      this._auth()
    }
  },
  onPullDownRefresh() {
    this.getRoomList()
  }
})